import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_audit_app/net/api_service.dart';
import 'package:flutter_audit_app/net/dio_utils.dart';
import 'package:flutter_audit_app/res/colors.dart';
import 'package:flutter_audit_app/res/dimens.dart';
import 'package:flutter_audit_app/res/strings.dart';
import 'package:flutter_audit_app/routes/fluro_navigator.dart';
import 'package:flutter_audit_app/routes/router_path.dart';
import 'package:flutter_audit_app/ui/login/bean/login_bean.dart';
import 'package:flutter_audit_app/utils/dialog/dialog_manager.dart';
import 'package:flutter_audit_app/utils/sputil_key.dart';
import 'package:flutter_audit_app/utils/toast.dart';
import 'package:flutter_audit_app/widgets/complex_text_field.dart';

//登录界面
class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool flag = false; //维护复选框状态
  TextEditingController _controllerName = new TextEditingController();
  TextEditingController _controllerPwd = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(

        ///https://blog.csdn.net/sinat_37255207/article/details/95448415（用来防止软键盘弹出时遮挡页面）
        ///方法一：resizeToAvoidBottomInset: false,设置此属性
        ///方法二：外层套SingleChildScrollView 元素内部不能和  Expanded 的flex 直接填充 会冲突
        /// 同时设置无效，无法达到输入框被遮挡解决的效果
        body: Stack(
      children: <Widget>[
        Image.asset(
          'assets/images/bg_login.png',
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          fit: BoxFit.cover,
        ),
        _loginLayout(),
      ],
    ));
  }

  //横屏布局
  Widget _loginLayout() {
    return Container(
      alignment: Alignment.topRight,
      margin: EdgeInsets.only(
        top: height(135),
        right: width(130),
      ),
      child: SingleChildScrollView(
        child: SizedBox(
          width: width(670),
          height: height(700),
          child: Card(
            color: Colors.white,
            child: Column(
              children: <Widget>[
                _logoWidget(),
                _textWidget(),
                ComplexTextField(
                  controller: _controllerName,
                  icon: Icons.person,
                  prefixText: Strings.userAccount,
                  labelText: 'username',
                  hintText: Strings.hintInputSignInTxt,
                  marginTop: 25,
                  textInputAction: TextInputAction.next,
                  keyboardType: TextInputType.emailAddress,
                ),
                ComplexTextField(
                  controller: _controllerPwd,
                  icon: Icons.lock,
                  prefixText: Strings.passwordTxt,
                  labelText: 'password',
                  hintText: Strings.hintPsdTxt,
                  marginTop: 15,
                  isObscure: true,
                  textInputAction: TextInputAction.done,
                  keyboardType: TextInputType.visiblePassword,
                ),
                _buildLoginButton(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  //Logo
  Widget _logoWidget() {
    return Padding(
      padding: EdgeInsets.only(top: height(40)),
      child: Image.asset(
        "assets/images/logo.png",
        width: width(130),
        height: height(130),
      ),
    );
  }

  //login text
  Widget _textWidget() {
    return Padding(
      padding: EdgeInsets.only(top: height(10)),
      child: Text(
        Strings.mobileAuditPlat,
        style: TextStyle(
          color: Color.fromARGB(255, 27, 101, 185),
          fontSize: 16,
        ),
        textAlign: TextAlign.center,
      ),
    );
  }

  //登录按钮
  Widget _buildLoginButton() {
    return Padding(
      padding: EdgeInsets.only(
        top: height(65),
//        bottom: height(115),
      ),
      child: Container(
        width: width(510),
        child: RaisedButton(
          color: Colours.blue_button,
          child: Text(
            Strings.signInTxt,
            style: TextStyle(
              color: Colors.white,
              fontSize: Dimens.gap_dp16,
            ),
          ),
          onPressed: () {
            _userLogin();
          },
        ),
      ),
    );
  }

  void _userLogin() {
    String username = _controllerName.text;
    String password = _controllerPwd.text;
    if (username.isEmpty) {
      Toast.show(Strings.hintInputUsernameTxt);
      return;
    }
    if (password.isEmpty || password.length < 6) {
      Toast.show(
          password.isEmpty ? Strings.hintInputPsdTxt : Strings.hint6PsdTxt);
      return;
    }
    DialogManager.showBasicDialog(context, msg: Strings.loginLoadingTxt);
    DioUtils.instance.asyncRequestNetwork<LoginBean>(
        Method.post, ApiService.user_login,
        body: {
          'loginNo': username,
          'pwd': EncryptUtil.encodeMd5(password),
          'rememberMe': false,
        }, onSuccess: (data) {
      SpUtil.putString(SpKey.accessToken, data.token);
      List<String> roleList = data.menuRoleList;
      if (roleList.isNotEmpty && roleList.contains(SpKey.keyAdmin)) {
        SpUtil.putBool(SpKey.keyAdmin, true);
      } else {
        SpUtil.putBool(SpKey.keyAdmin, false);
      }

      ///登录成功进入主界面
      NavigatorUtils.push(context, RouterPath.home,
          replace: true, clearStack: true);
    }, onError: (int code, String msg) {
      Toast.show(msg);
    }, onCompleted: () {
      NavigatorUtils.goBack(context);
    });
  }
}
